import registnet.dao.Student;
import registnet.dao.StudentPeer;
import registnet.dao.DegreeCoursePeer;
import registnet.dao.CurriculumPeer;
import registnet.dao.SystemPropertiesPeer;
import registnet.dao.SystemProperties;

import registnet.base.utility.AcademicRecordsUtility;

import resources.Constants;

StudentPeer studentPeer = new StudentPeer();
Student student;

List data = new Vector();
List resultSet = new Vector();

/* [start] 	initializes gui variables */
String _instance = bundle.getProperty("registnet.module.data_management.student");
String _instances = bundle.getProperty("registnet.module.data_management.students");

String _add = bundle.getProperty("registnet.module.data_management.actions.menu.add");
String _edit = bundle.getProperty("registnet.module.data_management.actions.menu.edit");
String _delete = bundle.getProperty("registnet.module.data_management.actions.menu.delete");
String _import = bundle.getProperty("registnet.module.data_management.actions.menu.import");
String _search = bundle.getProperty("registnet.module.data_management.actions.menu.search");
String _show_all = bundle.getProperty("registnet.module.data_management.actions.menu.show_all");

String _registrar = Constants.REGISTRAR;
String _college = Constants.COLLEGE;
String _unit = Constants.UNIT;

String _default_photo = bundle.getProperty("registnet.module.data_management.macro.students.form.default_photo");
String _student_number = bundle.getProperty("registnet.module.data_management.macro.students.form.student_number");
String _first_name = bundle.getProperty("registnet.module.data_management.macro.students.form.first_name");
String _middle_name = bundle.getProperty("registnet.module.data_management.macro.students.form.middle_name");
String _last_name = bundle.getProperty("registnet.module.data_management.macro.students.form.last_name");
String _sex = bundle.getProperty("registnet.module.data_management.macro.students.form.sex");
String _citizenship = bundle.getProperty("registnet.module.data_management.macro.students.form.citizenship");
String _degree_course = bundle.getProperty("registnet.module.data_management.macro.students.form.degree_course");
String _curriculum = bundle.getProperty("registnet.module.data_management.macro.students.form.curriculum");
String _birth_date = bundle.getProperty("registnet.module.data_management.macro.students.form.birth_date");
String _signature = bundle.getProperty("registnet.module.data_management.macro.students.form.signature");
String _civil_status = bundle.getProperty("registnet.module.data_management.macro.students.form.civil_status");
String _college_address = bundle.getProperty("registnet.module.data_management.macro.students.form.college_address");
String _residential_address = bundle.getProperty("registnet.module.data_management.macro.students.form.residential_address");
String _zip_code = bundle.getProperty("registnet.module.data_management.macro.students.form.zip_code");
String _country = bundle.getProperty("registnet.module.data_management.macro.students.form.country");
String _telephone_number = bundle.getProperty("registnet.module.data_management.macro.students.form.telephone_number");
String _cellphone_number = bundle.getProperty("registnet.module.data_management.macro.students.form.cellphone_number");
String _email = bundle.getProperty("registnet.module.data_management.macro.students.form.email");
String _father = bundle.getProperty("registnet.module.data_management.macro.students.form.father");
String _mother = bundle.getProperty("registnet.module.data_management.macro.students.form.mother");
String _guardian = bundle.getProperty("registnet.module.data_management.macro.students.form.guardian");
String _guardian_name = bundle.getProperty("registnet.module.data_management.macro.students.form.guardian_name");
String _guardian_contact = bundle.getProperty("registnet.module.data_management.macro.students.form.guardian_contact");
String _guardian_address = bundle.getProperty("registnet.module.data_management.macro.students.form.guardian_address");
String _guardian_relationship = bundle.getProperty("registnet.module.data_management.macro.students.form.guardian_relationship");
String _guardian_email = bundle.getProperty("registnet.module.data_management.macro.students.form.guardian_email");
String _high_school = bundle.getProperty("registnet.module.data_management.macro.students.form.high_school");
String _high_school_name = bundle.getProperty("registnet.module.data_management.macro.students.form.high_school_name");
String _high_school_grade = bundle.getProperty("registnet.module.data_management.macro.students.form.high_school_grade");
String _miscellaneous = bundle.getProperty("registnet.module.data_management.macro.students.form.miscellaneous");
String _is_rgep = bundle.getProperty("registnet.module.data_management.macro.students.form.is_rgep");
String _stfap_bracket = bundle.getProperty("registnet.module.data_management.macro.students.form.stfap_bracket");
String _adviser = bundle.getProperty("registnet.module.data_management.macro.students.form.adviser");
String _save = bundle.getProperty("registnet.module.data_management.macro.students.form.save");
String _cancel = bundle.getProperty("registnet.module.data_management.macro.students.form.cancel");
String _form_search = bundle.getProperty("registnet.module.data_management.macro.students.form.search");
String _required_fields = bundle.getProperty("registnet.module.data_management.macro.students.form.required_fields");
String _coursework = bundle.getProperty("registnet.module.data_management.macro.students.form.coursework");

String _icon_add = bundle.getProperty("registnet.icons.add");
String _icon_edit = bundle.getProperty("registnet.icons.edit");
String _icon_delete = bundle.getProperty("registnet.icons.delete");
String _icon_import = bundle.getProperty("registnet.icons.import");
String _icon_search = bundle.getProperty("registnet.icons.search");
String _icon_show_all = bundle.getProperty("registnet.icons.show_all");

String _actions = bundle.getProperty("registnet.module.student_records.macro.form5.form.actions");
String _export = bundle.getProperty("registnet.module.student_records.macro.form5.form.actions.export");
String _print = bundle.getProperty("registnet.module.student_records.macro.form5.form.actions.print");
/* [end] */

/* setting the user for logs */
if(_user_type.equals(_registrar))
	studentPeer.setUser(_user, _registrar);
else
	studentPeer.setUser(_user, _office);
/* [end] */

boolean isShowingInfo;
boolean isSearching;

ArrayList parentList = new ArrayList();
Map mapSTN_parent = new HashMap();
Map mapAL_parent = new HashMap();
Map mapAL_child = new HashMap();
Map map_treeitem = new HashMap();
SimpleTreeNode root = new SimpleTreeNode("ROOT", parentList);

public class MyTreeitemRenderer implements TreeitemRenderer {

	public void render(Treeitem item, Object data) throws Exception {
		
		String str = data.toString();
		
		Treerow tr = null;
		
		Treecell tc = new Treecell(str);
		if(item.getTreerow()==null){
			tr = new Treerow();
			tr.setParent(item);
			map_treeitem.put(str, item);
		}else{
			tr = item.getTreerow(); 
			tr.getChildren().clear();
		}
		tc.setParent(tr);
	}
}

public void retrieveObjects(){
	try{
	map_treeitem.clear();
	mapSTN_parent.clear();
	mapAL_parent.clear();
	mapAL_child.clear();
	parentList.clear();
	
	HashMap batch_leaf = new HashMap();
	HashMap batch_child = new HashMap();
	List students;
	if (_user_type.equals("Registrar"))
		students = studentPeer.getAllStudents();
	else if (_user_type.equals("College"))
		students = studentPeer.getStudentByCollege(new CollegePeer().getCollegeId(_office));
	for(int i=0; i<students.size(); i++){
		registnet.dao.Student student = students.get(i);
		String batch = student.getStudentNumber().substring(0, 4);
		if (!batch_leaf.containsKey(batch)){
			batch_leaf.put(batch, new ArrayList());
			batch_child.put(batch, new ArrayList());
		}
		SimpleTreeNode stnChild = new SimpleTreeNode(student.getStudentNumber(), new ArrayList());
		batch_leaf.get(batch).add(student.getStudentNumber());
		batch_child.get(batch).add(stnChild);
	}
	
	Set batch_key = batch_leaf.keySet();
	Iterator iter = batch_key.iterator();
	
	while(iter.hasNext()){
		String batch = iter.next();
		SimpleTreeNode stnParent = new SimpleTreeNode(batch, batch_child.get(batch));
		mapSTN_parent.put(batch, stnParent);
		mapAL_parent.put(batch, batch_child.get(batch));
		mapAL_child.put(batch, batch_leaf.get(batch));
		parentList.add(stnParent);
	}

	SimpleTreeNode root = new SimpleTreeNode("ROOT", parentList);
	SimpleTreeModel stm = new SimpleTreeModel(root);
	instance_tree.setModel(stm);
	instance_tree.setTreeitemRenderer(new MyTreeitemRenderer());
	}catch(Exception e){e.printStackTrace();}
}

void showAll(){
	
	retrieveObjects();
	
	try{
		instance_tree.setSelectedItem(map_treeitem.get(parentList.get(0).getData()));
	}catch(Exception e){}

	try{
		title.setValue("");
		contents.removeChild(contents.getFirstChild());
	}catch(Exception e ){}
}


public class SelectEventListener implements EventListener {
	
	public SelectEventListener (){
	}
			
	public void onEvent(Event event) throws UiException {
		
		if (instance_tree.getSelectedCount() == 1){
			if (instance_tree.getSelectedItem().getParentItem() != null){
				student = studentPeer.getStudent(instance_tree.getSelectedItem().getLabel());
				showInfo();
			}
		}
		else if (instance_tree.getSelectedCount() > 1)
			title.setValue("" + instance_tree.getSelectedCount() + " " + _instance + " selected");
		else
			title.setValue("");
	}
}

private class CancelEventListener implements EventListener {
	public SubmitEventListener (){
	}
			
	public void onEvent(Event event) throws UiException {
		instance_tree.clearSelection();
		try{
			title.setValue("");
			contents.removeChild(contents.getFirstChild());
		} catch (Exception e) {}
	}
}

private class SearchEventListener implements EventListener {
	
	public SearchEventListener (){
	}
			
	public void onEvent(Event event) throws UiException {
		
		int isConfirmed = Messagebox.show("Do you want to use the Search Result Viewer?", "", Messagebox.YES | Messagebox.NO, Messagebox.QUESTION);
		if (isConfirmed == Messagebox.YES){
			resultSet = curriculumPeer.searchCurriculum(curriculum_code.value, curriculum_name.value, new DegreeCoursePeer().getDegreeCourseId(degree.value));
			showSearchResultViewer();
			}
		else
			returnSearchResults();
			
		try{
			title.setValue("");
			contents.removeChild(contents.getFirstChild());
		} catch (Exception e) {}
	}
}	

void returnSearchResults(){
	
	map_treeitem.clear();
	mapSTN_parent.clear();
	mapAL_parent.clear();
	mapAL_child.clear();
	parentList.clear();
	
	ArrayList alChild = new ArrayList();
	ArrayList alLeaf = new ArrayList();
	for(int i=0; i<resultSet.size(); i++){
		SimpleTreeNode stnChild = new SimpleTreeNode(resultSet.get(i).getStudentNumber(), new ArrayList());
		alChild.add(stnChild);
		alLeaf.add(resultSet.get(i).getStudentNumber());
	}
	
	SimpleTreeNode parentNode = new SimpleTreeNode("Search Result", alChild);
	parentList.add(parentNode);
	
	mapSTN_parent.put("Search Result", parentNode);
	mapAL_parent.put("Search Result", alChild);
	mapAL_child.put("Search Result", alLeaf);
	
	SimpleTreeNode root = new SimpleTreeNode("ROOT", parentList);
	SimpleTreeModel stm = new SimpleTreeModel(root);
	instance_tree.setModel(stm);
	
	if (map_treeitem.get("Search Result").getTreechildren() != null)
		map_treeitem.get("Search Result").setOpen(true);
}
	
void showInfo(){

	isShowingInfo = true;
	isSearching = false;

	if (contents.getFirstChild() != null){
		contents.removeChild(contents.getFirstChild());
	}
		try{
				Component show_instance_form = Executions.createComponents("/WEB-INF/macros/data_management/student_form.zul", contents, null);
				title.setValue("Student Information");
				show_instance_form.getFellow("student_number_l").setValue(student.getStudentNumber());
				show_instance_form.getFellow("first_name_l").setValue(student.getFirstName());
				show_instance_form.getFellow("middle_name_l").setValue(student.getMiddleName());
				show_instance_form.getFellow("last_name_l").setValue(student.getLastName());
				show_instance_form.getFellow("sex_l").setValue(Constants.MAP_SEX_KEY.get(student.getSex()));
				show_instance_form.getFellow("citizenship_l").setValue(Constants.MAP_CITIZENSHIP_KEY.get(student.getCitizenship()));
				show_instance_form.getFellow("degree_l").setValue(new DegreeCoursePeer().getDegreeCourse(student.getCurriculum().getDegreeId()).getDegreeCode());
				show_instance_form.getFellow("curri_l").setValue(student.getCurriculum().getCurriculumCode());
				
				try{
					if (student.getBirthDate() == null || student.getBirthDate().length() == 0){
						show_instance_form.getFellow("birth_date_l").setValue("Not Available");
						show_instance_form.getFellow("birth_date_l").setStyle("font-style: italic;");						
					}
					else{
						show_instance_form.getFellow("birth_date_l").setValue(student.getBirthDate());
						show_instance_form.getFellow("birth_date_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getSignature() == null){
						show_instance_form.getFellow("signature_i").detach();
						show_instance_form.getFellow("signature_l").setValue("Not Available");
						show_instance_form.getFellow("signature_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("signature_i").setContent(new org.zkoss.image.AImage("signature: " + student.getStudentNumber(), student.getSignature()));
					}
				}catch(Exception e){}
				
				try{
					if (student.getPhoto() == null){
						show_instance_form.getFellow("photo_i").setContent(new org.zkoss.image.AImage(new java.net.URL("http://localhost:8080/RegistNet/imgs/head_silhouette.jpg")));
					}
					else{
						show_instance_form.getFellow("photo_i").setContent(new org.zkoss.image.AImage("photo: " + student.getStudentNumber(), student.getPhoto()));
					}
				}catch(Exception e){}
				
				if(student.getCivilStatus() != null && student.getCivilStatus() != 0){
					show_instance_form.getFellow("civil_status_l").setValue(Constants.CIVIL_STATUS[student.getCivilStatus() - 1]);
				}
				else{
					show_instance_form.getFellow("civil_status_l").setValue("Not Available");
					show_instance_form.getFellow("civil_status_l").setStyle("font-style: italic;");
				}
				
				try{
					if (student.getCollegeAddress() == null || student.getCollegeAddress().equals("")){
						show_instance_form.getFellow("college_add_l").setValue("Not Available");
						show_instance_form.getFellow("college_add_l").setStyle("font-style: italic;");						
					}
					else{
						show_instance_form.getFellow("college_add_l").setValue(student.getCollegeAddress());
						show_instance_form.getFellow("college_add_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getResidentialAddress() == null || student.getResidentialAddress().equals("")){
						show_instance_form.getFellow("residential_add_l").setValue("Not Available");
						show_instance_form.getFellow("residential_add_l").setStyle("font-style: italic;");						
					}
					else{
						show_instance_form.getFellow("residential_add_l").setValue(student.getResidentialAddress());
						show_instance_form.getFellow("residential_add_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getZipcode() == null || student.getZipcode().toString().equals("0")){
						show_instance_form.getFellow("zip_code_l").setValue("Not Available");
						show_instance_form.getFellow("zip_code_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("zip_code_l").setValue(student.getZipcode().toString());
						show_instance_form.getFellow("zip_code_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){  }
				
				try{
					if (student.getCountry() == null || student.getCountry().length() == 0){
						show_instance_form.getFellow("country_l").setValue("Not Available");
						show_instance_form.getFellow("country_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("country_l").setValue(student.getCountry());
						show_instance_form.getFellow("country_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getTelephoneNumber() == null || student.getTelephoneNumber().length() == 0){
						show_instance_form.getFellow("telephone_number_l").setValue("Not Available");
						show_instance_form.getFellow("telephone_number_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("telephone_number_l").setValue(student.getTelephoneNumber());
						show_instance_form.getFellow("telephone_number_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getCellphoneNumber() == null || student.getCellphoneNumber().length() == 0){
						show_instance_form.getFellow("cellphone_number_l").setValue("Not Available");
						show_instance_form.getFellow("cellphone_number_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("cellphone_number_l").setValue(student.getCellphoneNumber());
						show_instance_form.getFellow("cellphone_number_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getEmail() == null || student.getEmail().length == 0){
						show_instance_form.getFellow("email_l").setValue("Not Available");
						show_instance_form.getFellow("email_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("email_l").setValue(student.getEmail());
						show_instance_form.getFellow("email_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getFather() == null || student.getFather().toString().equals("")){
						show_instance_form.getFellow("father_l").setValue("Not Available");
						show_instance_form.getFellow("father_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("father_l").setValue(student.getFather());
						show_instance_form.getFellow("father_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getMother() == null || student.getMother().toString().equals("")){
						show_instance_form.getFellow("mother_l").setValue("Not Available");
						show_instance_form.getFellow("mother_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("mother_l").setValue(student.getMother());
						show_instance_form.getFellow("mother_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getGuardian() == null || student.getGuardian().toString().equals("")){
						show_instance_form.getFellow("guardian_l").setValue("Not Available");
						show_instance_form.getFellow("guardian_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("guardian_l").setValue(student.getGuardian());
						show_instance_form.getFellow("guardian_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getGuardianContactNumber() == null || student.getGuardianContactNumber().length() == 0){
						show_instance_form.getFellow("g_contact_number_l").setValue("Not Available");
						show_instance_form.getFellow("g_contact_number_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("g_contact_number_l").setValue(student.getGuardianContactNumber());
						show_instance_form.getFellow("g_contact_number_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getGuardianAddress() == null || student.getGuardianAddress().length() == 0){
						show_instance_form.getFellow("g_add_l").setValue("Not Available");
						show_instance_form.getFellow("g_add_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("g_add_l").setValue(student.getGuardianAddress());
						show_instance_form.getFellow("g_add_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getGuardianRelation() == null || student.getGuardianRelation().length() == 0){
						show_instance_form.getFellow("g_relation_l").setValue("Not Available");
						show_instance_form.getFellow("g_relation_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("g_relation_l").setValue(student.getGuardianRelation());
						show_instance_form.getFellow("g_relation_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getGuardianEmail() == null || student.getGuardianEmail().length() == 0){
						show_instance_form.getFellow("g_email_l").setValue("Not Available");
						show_instance_form.getFellow("g_email_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("g_email_l").setValue(student.getGuardianEmail());
						show_instance_form.getFellow("g_email_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getHighSchool() == null || student.getHighSchool().equals("")){
						show_instance_form.getFellow("high_school_l").setValue("Not Available");
						show_instance_form.getFellow("high_school_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("high_school_l").setValue(student.getHighSchool());
						show_instance_form.getFellow("high_school_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					if (student.getHighSchoolGrade() == null || student.getHighSchoolGrade().toString().equals("0.0")){
						show_instance_form.getFellow("high_school_grade_l").setValue("Not Available");
						show_instance_form.getFellow("high_school_grade_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("high_school_grade_l").setValue(student.getHighSchoolGrade().toString());
						show_instance_form.getFellow("high_school_grade_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				try{
					show_instance_form.getFellow("is_rgep_l").setValue(Constants.MAP_ANSWER_VALUE.get(student.getIsRGEP()));
				}catch(Exception e){}
				
				try{
					show_instance_form.getFellow("stfap_bracket_l").setValue(Constants.STFAP_BRACKET[student.getSTFAPBracket() - 1]);
				}catch(Exception e){}
				
				try{
					if (student.getAdviser() == null || student.getAdviser().length() == 0){
						show_instance_form.getFellow("adviser_l").setValue("Not Available");
						show_instance_form.getFellow("adviser_l").setStyle("font-style: italic;");
					}
					else{
						show_instance_form.getFellow("adviser_l").setValue(student.getAdviser());
						show_instance_form.getFellow("adviser_l").setStyle("font-weight: bold;");
					}
				}catch(Exception e){}
				
				show_instance_form.getFellow("save_btn").detach();
				show_instance_form.getFellow("cancel_btn").detach();
	}catch (Exception e) { }
}


void showForm(String action){

	isShowingInfo = false;
	isSearching = false;

	try{
		contents.removeChild(contents.getFirstChild());
	} catch (Exception e) {}

	
	if (action.equals(_edit)){
		if(instance_tree.getSelectedCount() == 1){
			if (instance_tree.getSelectedItem().getParentItem() != null){
				student = studentPeer.getStudent(instance_tree.getSelectedItem().getLabel());
				Component edit_instance_form = Executions.createComponents("/WEB-INF/macros/data_management/student_form.zul", contents, null);
				title.setValue(_edit + " " + student.getStudentNumber());
				
				edit_instance_form.getFellow("batch").setValue(student.getStudentNumber().substring(0,4));
				edit_instance_form.getFellow("identifier").setValue(student.getStudentNumber().substring(5,10));
				edit_instance_form.getFellow("first_name").setValue(student.getFirstName());
				edit_instance_form.getFellow("middle_name").setValue(student.getMiddleName());
				edit_instance_form.getFellow("last_name").setValue(student.getLastName());
				edit_instance_form.getFellow("sex").setValue(Constants.MAP_SEX_KEY.get(student.getSex()));
				if (student.getSex().equals(Constants.MALE)){
					edit_instance_form.getFellow("sex").setSelectedIndex(0);
				}
				else if (student.getSex().equals(Constants.FEMALE)){
					edit_instance_form.getFellow("sex").setSelectedIndex(1);
				}
				edit_instance_form.getFellow("citizenship").setValue(Constants.MAP_CITIZENSHIP_KEY.get(student.getCitizenship()));
				edit_instance_form.getFellow("citizenship").setSelectedIndex(student.getCitizenship() - 1);
					
				edit_instance_form.getFellow("degree").setValue(new DegreeCoursePeer().getDegreeCourse(student.getCurriculum().getDegreeId()).getDegreeCode());
				edit_instance_form.getFellow("curri").setValue(student.getCurriculum().getCurriculumCode());
				edit_instance_form.getFellow("birth_date").setText(student.getBirthDate());
				
				if(student.getCivilStatus() != null && student.getCivilStatus() != 0){
					edit_instance_form.getFellow("civil_status").setValue(Constants.CIVIL_STATUS[student.getCivilStatus() - 1]);
				}
				
				edit_instance_form.getFellow("college_add").setValue(student.getCollegeAddress());
				edit_instance_form.getFellow("residential_add").setValue(student.getResidentialAddress());
				try{
					edit_instance_form.getFellow("zip_code").setValue(student.getZipcode().toString());
				}catch(Exception e){ }
				edit_instance_form.getFellow("country").setValue(student.getCountry());
				edit_instance_form.getFellow("telephone_number").setValue(student.getTelephoneNumber());
				edit_instance_form.getFellow("cellphone_number").setValue(student.getCellphoneNumber());
				try{
				edit_instance_form.getFellow("email").setValue(student.getEmail());
				}catch(Exception e){ }
				edit_instance_form.getFellow("father").setValue(student.getFather());
				edit_instance_form.getFellow("mother").setValue(student.getMother());
				edit_instance_form.getFellow("guardian").setValue(student.getGuardian());
				edit_instance_form.getFellow("g_contact_number").setValue(student.getGuardianContactNumber());
				edit_instance_form.getFellow("g_add").setValue(student.getGuardianAddress());
				edit_instance_form.getFellow("g_relation").setValue(student.getGuardianRelation());
				try{
				edit_instance_form.getFellow("g_email").setValue(student.getGuardianEmail());
				}catch(Exception e){ }
				edit_instance_form.getFellow("high_school").setValue(student.getHighSchool());
				edit_instance_form.getFellow("high_school_grade").setValue(student.getHighSchoolGrade());
				try{
				edit_instance_form.getFellow("is_rgep").setValue(Constants.MAP_ANSWER_VALUE.get(student.getIsRGEP()));
				}catch(Exception e){}
				edit_instance_form.getFellow("stfap_bracket").setValue(Constants.STFAP_BRACKET[student.getSTFAPBracket() - 1]);
				edit_instance_form.getFellow("adviser").setValue(student.getAdviser());
				
				edit_instance_form.getFellow("save_btn").addEventListener("onClick", new SubmitEventListener(action));
				edit_instance_form.getFellow("cancel_btn").addEventListener("onClick", new CancelEventListener());
			}
			else
				title.setValue("");
		}
		else
			alert("Select one " + _instance);
	}
	
	else if (action.equals(_add)){
		Component add_instance_form = Executions.createComponents("/WEB-INF/macros/data_management/student_form.zul", contents, null);
		title.setValue(_add + " " + _instance);
		instance_tree.clearSelection();
		add_instance_form.getFellow("save_btn").addEventListener("onClick", new SubmitEventListener(action));
		add_instance_form.getFellow("cancel_btn").addEventListener("onClick", new CancelEventListener());
	}
	
	
}

void importData(){
	org.zkoss.util.media.Media media = Fileupload.get();
	if(media != null){
		java.io.Reader r = new java.io.BufferedReader(media.getReaderData());
		String line = null;
		StringBuffer buf = new StringBuffer(9999999);
		while ((line = r.readLine()) != null) {
			buf.append(line+"\r\n"); 
		}
		studentPeer.importStudents(buf.toString());
		retrieveObjects(); 
		title.setValue(_import + " " + _instance + " " + "successful");
	}
}

void createNewStudent(){
	if (isValid()){

		
		Integer civilStatusValue;
		try{
			civilStatusValue = Integer.parseInt(civil_status.getSelectedItem().getValue().toString());
		}catch(Exception e) { civilStatusValue = null; }
		
		Integer STFAPBracketValue;
		try{
			STFAPBracketValue = Integer.parseInt(stfap_bracket.getSelectedItem().getValue());
		}catch(Exception e) { STFAPBracketValue = 9; }
		
		String gEmailValue;
		try{
			gEmailValue = g_email.getText();
		} catch (Exception e) { gEmailValue = null; }
		
		
		String emailValue;
		try{
			emailValue = email.getText();
		} catch (Exception e) { emailValue = null; }
		
		Integer isRGEPValue;
		try{
			isRGEPValue = Integer.parseInt(is_rgep.getSelectedItem().getValue());
		} catch (Exception e) { isRGEPValue = 1; }
		
		
		Integer zipCodeValue;
		try{
			zipCodeValue = Integer.parseInt(zip_code.getText());
		} catch (Exception e) { zipCodeValue = null; }
		
		
		
		Double highSchoolGradeValue;
		try{
			if (high_school_grade.value == null)
				highSchoolGradeValue = 0.00;
			
			else
				highSchoolGradeValue = high_school_grade.value;
				
		}catch(Exception e ) { highSchoolGradeValue = 0.00; }
		
		

		if (studentPeer.createNewStudent(batch.value+"-"+identifier.value, first_name.value, middle_name.value, last_name.value, sex.getSelectedItem().getValue(), birth_date.getText(), civilStatusValue, residential_add.value, college_add.value, father.value, mother.value, guardian.value, g_contact_number.value, g_add.value, g_relation.value, gEmailValue, isRGEPValue, zipCodeValue, telephone_number.value, cellphone_number.value, high_school.value, highSchoolGradeValue, emailValue, STFAPBracketValue, signature.getContent().getByteData(), adviser.value, new Integer(citizenship.getSelectedItem().getValue()), country.value, new CurriculumPeer().getCurriculumId(curri.value), photo.getContent().getByteData()) != null){
			
			/*initialize the student's academic records */
			//SystemProperties sp = new SystemPropertiesPeer().getSystemProperties();
			//AcademicRecordsUtility.initializeAcademicRecords(studentPeer.getStudent(batch.value+"-"+identifier.value), sp.getSemester(), sp.getAcademicYear());
			
			title.setValue(_add + " " + _instance + " " + "successful");
			SimpleTreeNode newNode = new SimpleTreeNode(batch.value+"-"+identifier.value, new ArrayList());
			String parentValue;
			boolean isNewParentCreated;
			
			if(mapAL_parent.containsKey(batch.value.toString())){
				parentValue = batch.value.toString();
				isNewParentCreated = false;
			}
			
			else if (mapAL_parent.containsKey("Search Result")){
				parentValue = "Search Result";
				isNewParentCreated = false;
			}
			
			else{
				parentValue = batch.value.toString();
				
				ArrayList alChild = new ArrayList();
				ArrayList alLeaf = new ArrayList();
				alLeaf.add(batch.value+"-"+identifier.value);
				alChild.add(newNode);
				
				SimpleTreeNode stnParent = new SimpleTreeNode(parentValue, alChild);
				mapSTN_parent.put(parentValue, stnParent);
				mapAL_parent.put(parentValue, alChild);
				mapAL_child.put(parentValue, alLeaf);
				parentList.add(stnParent);
				
				instance_tree.getModel().fireEvent(root, mapSTN_parent.size() - 1, mapSTN_parent.size() - 1, org.zkoss.zul.event.TreeDataEvent.INTERVAL_ADDED);
				
				isNewParentCreated = true;
				
			}
			
			if (!isNewParentCreated){
				mapAL_parent.get(parentValue).add(newNode);
				mapAL_child.get(parentValue).add(batch.value+"-"+identifier.value);
				if(mapAL_parent.get(parentValue).size() == 1){
					instance_tree.renderItem(map_treeitem.get(parentValue));
					map_treeitem.get(parentValue).setOpen(true);
				}
				else
					instance_tree.getModel().fireEvent(mapSTN_parent.get(parentValue), mapAL_parent.get(parentValue).size() - 1, mapAL_parent.get(parentValue).size() - 1, org.zkoss.zul.event.TreeDataEvent.INTERVAL_ADDED);
			}
			
								
			try{
				contents.removeChild(contents.getFirstChild());
			} catch (Exception e) { }
		}
		else
			alert("Check info supplied");
	}
	else
		alert("Check info supplied");
}

void editStudent(){
	if (isValid()){
		try{
			Integer civilStatusValue;
			try{
				civilStatusValue = Integer.parseInt(civil_status.getSelectedItem().getValue().toString());
			}catch(Exception e) { civilStatusValue = null; }
		
			Integer STFAPBracketValue;
				try{
				STFAPBracketValue = Integer.parseInt(stfap_bracket.getSelectedItem().getValue());
			}catch(Exception e) { STFAPBracketValue = 9; }
		
			String gEmailValue;
			try{
				gEmailValue = g_email.getText();
			} catch (Exception e) { gEmailValue = null; }
		
		
			String emailValue;
			try{
				emailValue = email.getText();
			} catch (Exception e) { emailValue = null; }
		
			Integer isRGEPValue;
			try{
				isRGEPValue = Integer.parseInt(is_rgep.getSelectedItem().getValue());
			} catch (Exception e) { isRGEPValue = 1; }
		
		
			Integer zipCodeValue;
			try{
				zipCodeValue = Integer.parseInt(zip_code.getText());
			} catch (Exception e) { zipCodeValue = null; }

			Double highSchoolGradeValue;
			try{
				if (high_school_grade.value == null)
					highSchoolGradeValue = 0.00;
			
				else
					highSchoolGradeValue = high_school_grade.value;
				
			}catch(Exception e ) { highSchoolGradeValue = 0.00; }
		
			String tempBatch = studentPeer.getStudent(instance_tree.getSelectedItem().getLabel()).getStudentNumber().substring(0, 4);
			if (studentPeer.updateStudent(studentPeer.getStudentId(instance_tree.getSelectedItem().getLabel()), batch.value+"-"+identifier.value, first_name.value, middle_name.value, last_name.value, sex.getSelectedItem().getValue(), birth_date.getText(), civilStatusValue, residential_add.value, college_add.value, father.value, mother.value, guardian.value, g_contact_number.value, g_add.value, g_relation.value, gEmailValue, isRGEPValue, zipCodeValue, telephone_number.value, cellphone_number.value, high_school.value, highSchoolGradeValue, emailValue, STFAPBracketValue, signature.getContent().getByteData(), adviser.value, new Integer(citizenship.getSelectedItem().getValue()), country.value, new CurriculumPeer().getCurriculumId(curri.value), photo.getContent().getByteData())){
				SimpleTreeNode newNode = new SimpleTreeNode(batch.value+"-"+identifier.value, new ArrayList());
				String parentValue;
				boolean isNewParentCreated;
				
				if(mapAL_parent.containsKey(batch.value.toString())){
					parentValue = batch.value.toString();
					isNewParentCreated = false;
				}
				
				else if (mapAL_parent.containsKey("Search Result")){
					parentValue = "Search Result";
					isNewParentCreated = false;
				}
				
				else{
					parentValue = batch.value.toString();
				
					ArrayList alChild = new ArrayList();
					ArrayList alLeaf = new ArrayList();
					alLeaf.add(batch.value+"-"+identifier.value);
					alChild.add(newNode);
				
					SimpleTreeNode stnParent = new SimpleTreeNode(parentValue, alChild);
					mapSTN_parent.put(parentValue, stnParent);
					mapAL_parent.put(parentValue, alChild);
					mapAL_child.put(parentValue, alLeaf);
					parentList.add(stnParent);
					
					instance_tree.getModel().fireEvent(root, mapSTN_parent.size() - 1, mapSTN_parent.size() - 1, org.zkoss.zul.event.TreeDataEvent.INTERVAL_ADDED);
				
					int index = mapAL_child.get(tempBatch).indexOf(instance_tree.getSelectedItem().getLabel());
					mapAL_parent.get(tempBatch).remove(index);
					mapAL_child.get(tempBatch).remove(index);					
					instance_tree.getModel().fireEvent(mapSTN_parent.get(tempBatch), index, index, org.zkoss.zul.event.TreeDataEvent.INTERVAL_REMOVED);
					
					if (mapSTN_parent.get(tempBatch).isLeaf())
						mapAL_parent.get(tempBatch).add(new SimpleTreeNode("", new ArrayList()));
				
					isNewParentCreated = true;
				
				}
				
				
				if (!isNewParentCreated){	
					
					if(tempBatch.equals(batch.value.toString()) || parentValue.equals("Search Result")){
						mapAL_parent.get(parentValue).set(mapAL_child.get(parentValue).indexOf(instance_tree.getSelectedItem().getLabel()), newNode);
						mapAL_child.get(parentValue).set(mapAL_child.get(parentValue).indexOf(instance_tree.getSelectedItem().getLabel()), batch.value+"-"+identifier.value);
					
						instance_tree.getModel().fireEvent(mapSTN_parent.get(parentValue), mapAL_child.get(parentValue).indexOf(batch.value+"-"+identifier.value), mapAL_child.get(parentValue).indexOf(batch.value+"-"+identifier.value), org.zkoss.zul.event.TreeDataEvent.CONTENTS_CHANGED);
					}
				
					else{
						mapAL_parent.get(parentValue).add(newNode);
						mapAL_child.get(parentValue).add(batch.value+"-"+identifier.value);
						if(mapAL_parent.get(parentValue).size() == 1){
							map_treeitem.get(parentValue).setOpen(false);
							instance_tree.renderItem(map_treeitem.get(parentValue));
							map_treeitem.get(parentValue).setOpen(true);
						}
						else{
							instance_tree.getModel().fireEvent(mapSTN_parent.get(parentValue), mapAL_parent.get(parentValue).size() - 1, mapAL_parent.get(parentValue).size() - 1, org.zkoss.zul.event.TreeDataEvent.INTERVAL_ADDED);
						}
					
						int index = mapAL_child.get(tempBatch).indexOf(instance_tree.getSelectedItem().getLabel());
						mapAL_parent.get(tempBatch).remove(index);
						mapAL_child.get(tempBatch).remove(index);					
						instance_tree.getModel().fireEvent(mapSTN_parent.get(tempBatch), index, index, org.zkoss.zul.event.TreeDataEvent.INTERVAL_REMOVED);
					
						if (mapSTN_parent.get(tempBatch).isLeaf()){
							mapAL_parent.get(tempBatch).add(new SimpleTreeNode("", new ArrayList()));
						}
						
					}
				}
				
				title.setValue(_edit + " " + _instance + " " + "successful");
				
				try{
					contents.removeChild(contents.getFirstChild());
				} catch (Exception e) { }
			}
			
			else
				alert("Check info supplied");
			
		} catch (Exception e) { alert("Check info supplied"); }
	
	}
	else
		alert("Check info supplied");
}

void delete(){
	if(instance_tree.getSelectedCount() != 0){
		int isConfirmed = Messagebox.show("Proceed?", _delete + " " + _instance, Messagebox.YES | Messagebox.NO, Messagebox.QUESTION);
		if (isConfirmed == Messagebox.YES){
			boolean isError = false;
			int errorCount = 0;
			Iterator i = instance_tree.getSelectedItems().iterator();
			List batches = new Vector();
			List studentNumbers = new Vector();
			
			while(i.hasNext()){
				Treeitem treeitem = i.next(); 
				Student temp = studentPeer.getStudent(treeitem.getLabel());
				if (temp != null){
					if (studentPeer.deleteStudent(temp.getStudentId())){
						batches.add(temp.getStudentNumber().substring(0, 4));
						studentNumbers.add(temp.getStudentNumber());
					}
					else{
						isError = true;
						errorCount++;
					}
				}
			}
			
			for(int i=0; i<batches.size(); i++){
				String parentValue;
				if(mapSTN_parent.containsKey("Search Result"))
					parentValue = "Search Result";
				else
					parentValue = batches.get(i);
				int index = mapAL_child.get(parentValue).indexOf(studentNumbers.get(i));
				mapAL_parent.get(parentValue).remove(index);
				mapAL_child.get(parentValue).remove(index);
				instance_tree.getModel().fireEvent(mapSTN_parent.get(parentValue), index, index, org.zkoss.zul.event.TreeDataEvent.INTERVAL_REMOVED);
				
				if (mapSTN_parent.get(parentValue).isLeaf())
					mapAL_parent.get(parentValue).add(new SimpleTreeNode("", new ArrayList()));
			}

			if (isError){ 
				alert(_delete + " " + "failed" + ": " + errorCount + " " + _instance);
				title.setValue(_delete + " " + _instance + " " + "failed");
			}
			
			else{
				title.setValue(_delete + " " + _instance + " " + "successful");
				if (contents.getFirstChild() != null){
					contents.removeChild(contents.getFirstChild());
				}
			}
		}			
	}
}


boolean isValid(){

	if (new String(batch.value+"-"+identifier.value).length() != 10)
		return false;
	if (first_name.value != null && first_name.value.trim().length() == 0)
		return false;
	if (middle_name.value != null && middle_name.value.trim().length() == 0)
		return false;
	if (last_name.value != null && last_name.value.trim().length() == 0)
		return false;
	if (sex.getSelectedItem() == null)
		return false;
	if (citizenship.getSelectedItem() == null)
		return false;
	return true;
}


private class SubmitEventListener implements EventListener {
	String submitType;
	public SubmitEventListener (String submitType){
		this.submitType = submitType; 
	}
			
	public void onEvent(Event event) throws UiException {
		if(this.submitType.equals(_add))
			createNewStudent();
		else if (this.submitType.equals(_edit))
			editStudent();
		instance_tree.clearSelection();
	}
}

private class CancelEventListener implements EventListener {
	public SubmitEventListener (){
	}
			
	public void onEvent(Event event) throws UiException {
		instance_tree.clearSelection();
		try{
			title.setValue("");
			contents.removeChild(contents.getFirstChild());
		} catch (Exception e) {}
	}
}



void filter(String string){

	ListIterator i = data.listIterator();
	List list = new java.util.Vector();
	while(i.hasNext()){
		String temp = i.next(); 
		if(temp.toUpperCase().startsWith(string.toUpperCase())){
			list.add(temp);
		}
	}
	instance_tree.getModel().clear();
	instance_tree.getModel().addAll(list);
}




void showSearchForm(){
	isSearching = true;
	isShowingInfo = false;

	try{
		contents.removeChild(contents.getFirstChild());
	} catch (Exception e) {}

	Component search_instance_form = Executions.createComponents("/WEB-INF/macros/data_management/student_form.zul", contents, null);
	title.setValue(_search + " " + _instance);
	instance_tree.clearSelection();
	search_instance_form.getFellow("search_btn").addEventListener("onClick", new SearchEventListener());
	search_instance_form.getFellow("cancel_btn").addEventListener("onClick", new CancelEventListener());
}

void showSearchResultViewer(){
	Tabbox stage = macro_win.getParent().getParent().getTabbox();
	Tab tab = new Tab("Search Result");
	Tabs tabs = stage.getTabs();
	tab.setClosable(true);
	tab.setParent(tabs);
	stage.setSelectedTab(tab);
		
	Tabpanel tabpanel = new Tabpanel();
	tabpanel.setSclass("background_light_blue");
	
	
	Component search_result_viewer = Executions.createComponents("/WEB-INF/macros/search_result_viewer.zul", tabpanel, null);
		
	Tabpanels tabpanels = stage.getTabpanels();
	tabpanel.setParent(tabpanels);
	stage.setSelectedPanel(tabpanel);
}


private class FieldItemRenderer implements ListitemRenderer {
	public void render(Listitem item, java.lang.Object data) {
		new Listcell(data).setParent(item);
	}
}
			
private class DataItemRenderer implements ListitemRenderer {
	public void render(Listitem item, java.lang.Object data) {
		for(int i=0; i<data.length; i++)
			new Listcell(data[i]).setParent(item);
	}
}
	
void retrieveFieldNames(){
	List data = new registnet.dao.Student().getFields();		  
	String[] listModel = new String[data.size()];
	for (int i=0; i<data.size(); i++)
		listModel[i] = data.get(i);
	ListModel strset = new ListModelList(listModel);
	field_list.setModel(strset);
	field_list.setItemRenderer(new FieldItemRenderer());
}


private class FieldEventListener implements EventListener {
	
	public FieldEventListener (){
	}

	public void onEvent(Event event) throws UiException {
		result_list.removeChild(result_list.getListhead());
		Listhead listhead = new Listhead();
		listhead.setParent(result_list);
		Object[] selected = field_list.getSelectedItems().toArray();
		for (int i=0; i<selected.length; i++){
			Listheader lh = new Listheader(field_list.getModel().get(selected[i].getIndex()));
			lh.setParent(listhead);
		}
		
		
		String[] temp = new String[resultSet.size()];
		int numRows = temp.length;
		String[][] listModel = new String[numRows][selected.length];
		for (int i=0; i<temp.length; i++){
			for (int j=0; j<selected.length; j++){
				if (field_list.getModel().get(selected[j].getIndex()).equals("Code"))
					listModel[i][j] = resultSet.get(i).getCourseCode();
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Name"))
					listModel[i][j] = resultSet.get(i).getCourseName();
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Description"))
					listModel[i][j] = resultSet.get(i).getCourseDescription();
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Credit"))
					listModel[i][j] = resultSet.get(i).getCredit().toString();
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Offered"))
					listModel[i][j] = resources.Constants.MAP_ANSWER_VALUE.get(resultSet.get(i).getOffered());
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Sem Offered"))
					listModel[i][j] = resources.Constants.MAP_SEMESTER_OFFERING_KEY.get(resultSet.get(i).getSemesterOffered());
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Prereq"))
					listModel[i][j] = grammar.Converter.prefixToInfix(resultSet.get(i).getPrerequisite());
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Lect Hrs"))
					listModel[i][j] = resultSet.get(i).getLectureHoursPerWeek().toString();
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Min Lect Stud"))
					listModel[i][j] = resultSet.get(i).getMinimumNumberOfLectureStudents().toString();
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Max Lect Stud"))
					listModel[i][j] = resultSet.get(i).getMaximumNumberOfLectureStudents().toString();
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Has Lab?"))
					listModel[i][j] = resources.Constants.MAP_ANSWER_VALUE.get(resultSet.get(i).getHasLaboratory());
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Lab Hrs"))
					listModel[i][j] = resultSet.get(i).getLaboratoryHoursPerWeek().toString();
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Min Lab Stud"))
					listModel[i][j] = resultSet.get(i).getMinimumNumberOfLaboratoryStudents().toString();
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Max Lab Stud"))
					listModel[i][j] = resultSet.get(i).getMaximumNumberOfLaboratoryStudents().toString();
				else if (field_list.getModel().get(selected[j].getIndex()).equals("Unit"))
					listModel[i][j] = resultSet.get(i).getUnit().getUnitCode();
			}
		}
		ListModel strset = new ListModelList(listModel);
		result_list.setModel(strset);
		result_list.setItemRenderer(new DataItemRenderer());
		
	}
}



void showCoursework(String studentNumber){
	title.setValue("Plan of Coursework");
	Component coursework_form = Executions.createComponents("/WEB-INF/macros/data_management/student_coursework.zul", contents, null);
	coursework_form.getFellow("student_number_l").setValue(studentNumber);
	coursework_form.getFellow("fullname_l").setValue(student.getLastName() + ", " + student.getFirstName() + " " + student.getMiddleName());
	coursework_form.getFellow("curriculum_l").setValue(student.getCurriculum().getCurriculumCode());
	contents.removeChild(contents.getFirstChild());
}